<template>
  <div v-if="info" class="approval-page">
    <!-- 左侧信息列 -->
    <div  class="left-column">
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <h3 class="card-title">基本信息</h3>
        <ul class="info-list">
          <li>
            <span class="label">单据编号</span>
            <span class="value">{{ info.checkoutNo }}</span>
          </li>
          <li>
            <span class="label">老人姓名</span>
            <span class="value">{{ info.name }}</span>
          </li>
          <li>
            <span class="label">老人身份证号</span>
            <span class="value">{{ info.idCardNo }}</span>
          </li>
          <li>
            <span class="label">联系方式</span>
            <span class="value">{{ info.contact }}</span>
          </li>
          <li>
            <span class="label">费用期限</span>
            <span class="value">{{ formatDateYmd(info.stayStart) }} —— {{ formatDateYmd(info.stayEnd) }}</span>
          </li>
          <li>
            <span class="label">护理等级</span>
            <span class="value">{{ info.careLevel }}</span>
          </li>
          <li>
            <span class="label">入住床位</span>
            <span class="value">{{ info.bedNo }}床位</span>
          </li>
          <li>
            <span class="label">签约合同</span>
            <span class="value">
              {{ info.name }}的入住解约协议.pdf
              <a :href="info.contractUrl" class="view-link" v-if="info.contractUrl">查看</a>
            </span>
          </li>
          <li>
            <span class="label">养老顾问</span>
            <span class="value">{{ info.consultant || '无' }}</span>
          </li>
          <li>
            <span class="label">护理员</span>
            <span class="value">{{ info.caregiverName }}</span>
          </li>
        </ul>
      </div>

      <!-- 申请信息卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">申请信息</h3>
        <ul class="info-list">
          <li>
            <span class="label">退住日期</span>
            <span class="value">{{ info.checkoutTime }}</span>
          </li>
          <li>
            <span class="label">退住原因</span>
            <span class="value">{{ info.checkoutReason }}</span>
          </li>
          <li>
            <span class="label">备注</span>
            <span class="value">{{ info.remark || '无' }}</span>
          </li>
          <li>
            <span class="label">申请人</span>
            <span class="value">{{ info.applicant }}</span>
          </li>
          <li>
            <span class="label">申请时间</span>
            <span class="value">{{ formatDateYmd(info.applyTime) }}</span>
          </li>
        </ul>
      </div>

      <!-- 解除记录卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">解除记录</h3>
        <ul class="info-list" v-if="info.contract">
          <li>
            <span class="label">提交人</span>
            <span class="value">{{ info.applicant }}</span>
          </li>
          <li>
            <span class="label">解除日期</span>
            <span class="value">{{ formatDateYmd(info.contract.terminateDate) }}</span>
          </li>
          <li>
            <span class="label">解除协议</span>
            <span class="value">
              {{ info.name }}的合同解除协议.pdf
              <a :href="info.contract.terminateAgreementUrl" class="view-link">查看</a>
            </span>
          </li>
        </ul>
      </div>

      <!-- 完成账单清算卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">完成账单清算</h3>
        <div class="settlement-section" v-if="info.checkoutBill && info.balance">
          <h4 class="section-subtitle">退款信息</h4>
          <ul class="info-list">
            <li>
              <span class="label">剩余预缴款</span>
              <span class="value">{{ info.balance.prepaidBalance.toFixed(2) }}元</span>
            </li>

            <li>
              <span class="label">退回押金</span>
              <span class="value">{{ info.balance.arrearsAmount.toFixed(2) }}元</span>
            </li>
            <li>
              <span class="label">应退金额</span>
              <span class="value">{{ info.checkoutBill.refundAmount.toFixed(2) }}元</span>
            </li>
          </ul>

          <h4 class="section-subtitle">退款凭证</h4>
          <ul class="info-list">
            <li>
              <span class="label">提交人</span>
              <span class="value">{{ info.applicant }}</span>
            </li>
            <li>
              <span class="label">提交时间</span>
              <span class="value">{{ formatDateYmd(info.checkoutBill.updatedAt) }}</span>
            </li>
            <li>
              <span class="label">退款凭证</span>
              <img
                  :src="info.checkoutBill.refundVoucherUrl"
                  alt="退款凭证"
                  class="certificate-img"
                  v-if="info.checkoutBill.refundVoucherUrl"
              />
            </li>
            <li>
              <span class="label">退款备注</span>
              <span class="value" v-if="info.checkoutBill.billJson">
                {{ JSON.parse(info.checkoutBill.billJson).adjustRemark1 || '无' }}
              </span>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 右侧操作记录列 -->
    <div class="right-column">
      <!-- 操作记录卡片 -->
      <div v-if="log.activities" class="record-card">
        <h3 class="card-title">操作记录</h3>
        <ul class="record-list">
          <!-- 发起申请记录 -->
          <li v-for="item in log.activities" class="record-item">
            <div class="item-icon">
              <!-- 替换为“发起申请”图标 -->
              <img src="@/assets/images/avatar.jpg" alt="发起申请" />
            </div>
            <div class="item-content">
              <div class="item-desc">({{ log[item.assignee]?.remark }}){{item.name}}</div>
              <div class="item-status"> {{ log[item.assignee]?.nickName }}({{item.endTime ? "已处理":"正在处理"}})</div>
              <div v-if="log[item.id] " class="approval-opinion">{{log[item.id].fullMessage ? log[item.id].fullMessage :"无"}}</div>
            </div>
            <div class="item-time">{{item.endTime ? formatDateStr(item.endTime):""}}</div>
          </li>

        </ul>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="btn-area">
      <el-button type="default" @click="goBack">返回</el-button>
    </div>
  </div>
</template>

<script>
import {checkOutDto, getActivityLog} from "@/api/check/checkout.js";

export default {
  name: "ApprovalPage",
  data() {
    return {
      info: {},
      log:{}// 存储接口返回的完整数据
    };
  },
  methods: {
    goBack() {
      this.$router.push("/CollaborationWork/tasking");// 路由回退
    },
    /**
     * 日期格式化：将ISO格式日期转换为"YYYY-MM-DD HH:mm:ss"
     * @param {string} dateStr - 接口返回的ISO日期字符串（如2025-10-18T18:01:58.000+08:00）
     * @returns {string} 格式化后的日期
     */
    formatDate(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())} ${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}:${this.padZero(date.getSeconds())}`;
    },
    formatDateYmd(dateStr) {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      // 仅保留年-月-日，去掉时分秒部分
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())}`;
    },
    formatDateStr(dateStr) {
      // 1. 基础校验：判断是否为有效字符串且包含关键符号
      if (!dateStr || typeof dateStr !== 'string' || !dateStr.includes('T')) {
        console.warn('输入不是有效的日期格式（需包含"T"，如2025-10-23T10:42:42.000+08:00）');
        return '';
      }

      // 2. 截取核心部分：年月日（T之前） + 时分秒（T之后、.之前）
      // 例："2025-10-23T10:42:42.000+08:00" → 拆分为 ["2025-10-23", "10:42:42.000+08:00"]
      const datePart = dateStr.split('T')[0]; // 取"T"前的年月日："2025-10-23"
      const timePart = dateStr.split('T')[1].split('.')[0]; // 取"T"后、"."前的时分秒："10:42:42"

      // 3. 重组为 "年月日 时分秒" 格式
      return `${datePart} ${timePart}`;
    },
    /**
     * 补零函数：确保日期数字为两位数（如1→01）
     * @param {number} num - 需要补零的数字
     * @returns {string} 补零后的字符串
     */
    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },
    /**
     * 护理等级转换：将数字等级转为文本（根据实际业务规则调整）
     * @param {string} level - 接口返回的护理等级数字（如"2"）
     * @returns {string} 护理等级文本
     */
    getCareLevelText(level) {
      const levelMap = {
        "1": "一级护理",
        "2": "二级护理",
        "3": "三级护理",
        "4": "特级护理"
      };
      return levelMap[level] || `等级${level}`;
    }
  },
  mounted() {
    // 调用接口获取数据（此处11为固定参数，实际应从路由/父组件传递）
    checkOutDto(this.id).then(res => {
      if (res.code === 200) {
        console.log(res.data)
        this.info = res.data; // 将接口返回的data赋值给info
      }
    });
    getActivityLog(this.id).then( res=>{
      this.log = res.data
      this.log.activities=res.data.activities.reverse()
      console.log(res)
    })
  },
  props: {
    id: {
      type: [Number,String],
      default: 0,
    },
  },
};
</script>
<style scoped>
.approval-page {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20px;
}

.left-column {
  width: 65%;
}

.right-column {
  width: 33%;
}

.info-card,
.record-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.info-list {
  list-style: none;
  padding: 0;
}

/* 标签右对齐样式 */
.info-list li {
  display: flex;
  margin-bottom: 15px;
}

.info-list .label {
  width: 120px;
  text-align: right;
  margin-right: 15px;
  color: #606266;
}

.info-list .value {
  flex: 1;
}

.view-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 5px;
}

/* 完成账单清算样式 */
.settlement-section .section-subtitle {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 15px;
}

.certificate-img {
  width: 150px;
  height: auto;
  border: 1px solid #ebeef5;
  margin-top: 5px;
}

/* 操作记录核心样式（流程线 + 布局） */
.record-list {
  list-style: none;
  padding: 0;
  position: relative; /* 作为伪元素的定位容器 */
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
}

/* 垂直主线：连接所有记录项（除第一个），从头像中间穿过 */
.record-item:not(:first-child)::before {
  content: '';
  position: absolute;
  left: 20px; /* 与40px宽图标中心对齐 */
  top: 0;
  height: 100%;
  width: 1px;
  background-color: #dcdcdc;
}

.item-icon {
  margin-right: 12px;
}

.item-icon img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.item-content {
  flex: 1;
}

.item-desc {
  font-weight: 500;
  margin-bottom: 2px;
}

.item-status {
  color: #909399;
  font-size: 12px;
}

/* 审批意见提示框 */
.approval-opinion {
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.item-time {
  color: #909399;
  font-size: 12px;
  white-space: nowrap; /* 防止时间换行 */
}

/* 底部按钮 */
.btn-area {
  margin-top: 40px;
  text-align: center;
  width: 100%;
}

.btn-area button {
  margin: 0 10px;
}
</style>